package com.shxy.api.service.impl;
import com.shxy.api.bean.user.RoleBean;
import com.shxy.api.bean.user.UserInfo;
import com.shxy.api.dao.user.RoleDao;
import com.shxy.api.dao.user.UserDao;
import com.shxy.api.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 登录信息管理
 */
@Service
public class LoginService implements ILoginService {
    @Autowired private UserDao userDao;
    @Autowired private RoleDao roleDao;

    @Override
    public String getUsernameById(String userId) {
        Optional<UserInfo> op = userDao.findById(userId);
        if(op.isPresent()) {
            return op.get().getUsername();
        }
        return null;
    }

    @Override
    public boolean isUserExist(String id) {
        return userDao.findById(id).isPresent();
    }

    @Override
    public boolean isUserNameExist(String username) {
        return userDao.existsByUsername(username);
    }

    @Override
    public String addUser(String username, String password, String realName, String phone) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setRealName(realName);
        userInfo.setPhone(phone);
        userInfo.setRole(roleDao.findByName("guest"));
        return userDao.save(userInfo).getId();
    }

    @Override
    public String addRole(String name, String note) {
        RoleBean role = new RoleBean();
        role.setName(name);
        role.setNote(note);
        return roleDao.save(role).getId();
    }

    @Override
    public boolean isRoleNameExist(String name) {
        return roleDao.existsByName(name);
    }

    @Override
    public UserInfo getUserById(String userId) {
        Optional<UserInfo> op = userDao.findById(userId);
        return op.isPresent() ? op.get() : null;
    }

    @Override
    public RoleBean getRoleById(String roleId) {
        Optional<RoleBean> op = roleDao.findById(roleId);
        return op.isPresent() ? op.get() : null;
    }

    @Override
    public String setUserRole(UserInfo user, RoleBean role) {
        user.setRole(role);
        return userDao.save(user).getId();
    }

    @Override
    public UserInfo getUserByName(String username) {
        return userDao.findByUsername(username);
    }
}
